<template>
  <TreeTableLayout>
    <template #tree>
      <Tree @query="doQuery" :gatewayType="0"></Tree>
    </template>
    <template #table>
      <RightTableLayout :slotName="['search', 'operation', 'table', 'pagination']">
        <template #search>
          <query :columns="columns" @query="doQuery"></query>
        </template>
        <template #operation>
          <div :class="{ btnbox: pid }">
            <el-button type="danger" @click="allLightNum">
              {{ i18n.language == "zh-cn" ? "开关灯值" : "Switchlightvalue" }}
            </el-button>
            <el-button type="primary" @click="allLightOn">
              {{ i18n.language == "zh-cn" ? "全部开灯" : "Alllightson" }}
            </el-button>
            <el-button type="primary" @click="allLightOff">
              {{ i18n.language == "zh-cn" ? "全部关灯" : "Turnoffalllights" }}
            </el-button>
            <el-button type="primary" @click="allLightAdjust">
              {{ i18n.language == "zh-cn" ? "全部调光" : "DimmingAll" }}
            </el-button>
            <el-button type="primary" @click="allAdjustColor">
              {{ i18n.language == "zh-cn" ? "全部调色" : "ColorAll" }}
            </el-button>
            <el-button type="primary" @click="lightOn">
              {{ i18n.language == "zh-cn" ? "开灯" : "turnonthelight" }}
            </el-button>
            <el-button type="primary" @click="lightOff">
              {{ i18n.language == "zh-cn" ? "关灯" : "Turnoffthelights" }}
            </el-button>
            <el-button type="primary" @click="adjustLight">
              {{ i18n.language == "zh-cn" ? "调光" : "Dimming" }}
            </el-button>
            <el-button type="primary" @click="adjustColor">
              {{ i18n.language == "zh-cn" ? "调色" : "toning" }}
            </el-button>
          </div>
        </template>
        <template #table>
          <el-table :empty-text="i18n.fy.nodata" :data="data.tableData" ref="multipleTableRef" border
            :style="{ width: getWidth(), height: getHeight() }" v-loading="data.loading"
            :element-loading-text="i18n.fy.loading" @selection-change="handleSelectionChange"
            @sort-change="sortChangeTable">
            <el-table-column type="selection" width="55" fixed />
            <el-table-column prop="macaddress" :label="i18n.fy.SerialNumber" width="70" align="center" fixed>
              <template #default="scope">
                {{ scope.$index * 1 + 1 + (data.queryForm.page - 1) * data.queryForm.limit }}
              </template>
            </el-table-column>
            <el-table-column prop="macaddress" :label="i18n.fy.MACAddress" width="150" fixed />
            <el-table-column prop="customName" :label="i18n.fy.DeviceAliases" width="150" :sortable="true" fixed
              :show-overflow-tooltip="true">
              <template #default="scope">
                <span v-if="scope.row.customName === '01'">CCO</span>
                <span v-else-if="scope.row.customName === '02'">STA</span>
                <span v-else-if="scope.row.customName === '03'">METER</span>
                <span v-else>
                  {{ scope.row.customName || "" }}
                </span>
              </template>
            </el-table-column>
            <el-table-column prop="deviceType" :label="i18n.fy.EquipmentName" :sortable="true" width="150" />
            <el-table-column prop="operatingStatus" :label="i18n.fy.DeviceStatus" :sortable="true" width="150">
              <template #default="scope">
                <span v-if="scope.row.operatingStatus === '01'" style="color: lawngreen">
                  {{ i18n.language == "zh-cn" ? "在线" : "online" }}
                </span>
                <span v-else-if="scope.row.operatingStatus === '00'" style="color: #ddd">
                  {{ i18n.language == "zh-cn" ? "离线" : "offline" }}
                </span>
                <span v-else>{{ scope.row.operatingStatus }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="areaCode" :label="i18n.fy.EquipmentArea" width="150" :sortable="true" />
            <el-table-column prop="groupName" :label="i18n.fy.EquipmentGroupNumber" width="220">
              <template #header="scope">
                <div style="display: flex" class="selectName">
                  {{ i18n.fy.EquipmentGroupNumber }}
                  <select v-model="customName" placeholder="" @change="setCustomName()">
                    <option v-for="item in options" :value="item.group_name">{{ item.name || item.group_name }}</option>
                  </select>
                </div>
              </template>
            </el-table-column>
            <el-table-column prop="luminance" :label="i18n.fy.CurrentBrightness" width="150"> </el-table-column>
            <el-table-column prop="triggerOpenLightNum" :label="i18n.fy.Someonebrightness" width="150">
            </el-table-column>
            <el-table-column prop="triggerFloodlightNum" :label="i18n.fy.Unmannedbrightness" width="150">
            </el-table-column>
            <el-table-column prop="darkenDelay" :label="i18n.fy.Delaytime" width="150"> </el-table-column>
            <el-table-column prop="colorTemperature" :label="i18n.fy.Currentchromaticity" width="150">
            </el-table-column>
            <el-table-column prop="hasTrigger" :label="i18n.fy.Sensingheadstatus" width="150"> </el-table-column>
            <el-table-column prop="sensorSensitivity" :label="i18n.fy.sensorSensitivity" width="150">
              <template #default="scope">
                <span v-if="scope.row.sensorSensitivity == 'FF'"></span>
                <span v-else>
                  {{ scope.row.sensorSensitivity }}
                </span>
              </template>
            </el-table-column>
            <el-table-column prop="luminanceChange" :label="i18n.fy.luminanceChange" width="150">
              <template #default="scope">
                {{ scope.row.luminanceChange }}
              </template>
            </el-table-column>
            <el-table-column prop="ratedPower" :label="i18n.fy.ratedPower" width="150"> </el-table-column>
            <el-table-column prop="kwh" :label="i18n.fy.electricity + '(KWH)'" width="150">
              <template #default="scope">
                {{ scope.row.kwh / 1000 }}
              </template>
            </el-table-column>
            <el-table-column prop="amp" :label="i18n.fy.power + '(KW)'" width="150">
              <template #default="scope">
                {{ scope.row.amp / 100 }}
              </template>
            </el-table-column>
            <el-table-column prop="watt" :label="i18n.fy.current + '(A)'" width="150">
              <template #default="scope">
                {{ scope.row.watt / 100 }}
              </template>
            </el-table-column>
            <el-table-column prop="softwareVersion" :label="i18n.fy.Version" width="150"> </el-table-column>
            <el-table-column prop="updateTime" :label="i18n.fy.updateTime" width="170"> </el-table-column>
          </el-table>
        </template>
        <template #pagination>
          <el-pagination @size-change="onChanSize" @current-change="onChanPage"
            v-model:current-page="data.queryForm.page" v-model:page-size="data.queryForm.limit" :total="data.total" />
        </template>
      </RightTableLayout>
    </template>
  </TreeTableLayout>
  <!-- 弹窗 -->
  <div id="slideDiv" style="display: none; padding: 20px; text-align: center">
    <div id="slideTest1"></div>
  </div>
  <div id="slideDiv2" style="display: none; padding: 20px; text-align: center">
    <div class="layui-form-item">
      <label class="layui-form-label">
        {{ i18n.language == "zh-cn" ? "关灯值" : "OffLightValue" }}
        :</label>
      <div class="layui-input-block">
        <div id="slide1"></div>
      </div>
    </div>
    <div class="layui-form-item">
      <label class="layui-form-label">
        {{ i18n.language == "zh-cn" ? "开灯值" : "LampOnValue" }}
        :</label>
      <div class="layui-input-block">
        <div id="slide2"></div>
      </div>
    </div>
  </div>
  <div id="lightTestDiv" style="display: none; padding: 20px; text-align: center">
    <form class="layui-form" action="">
      <div class="layui-form-item">
        <label class="layui-form-label">
          {{ i18n.language == "zh-cn" ? "开关值" : "switchValue" }}
          :</label>
        <div class="layui-input-block">
          <input type="radio" name="lTest" value="0" title="开" checked="" />
          <input type="radio" name="lTest" value="1" title="关" />
        </div>
      </div>
    </form>
  </div>
  <div id="lightNameDiv" style="display: none; padding: 20px; text-align: center">
    <form class="layui-form" action="">
      <div class="layui-form-item">
        <div class="layui-inline">
          <div class="lightNameDiv">
            <label class="layui-form-label">
              {{ i18n.language == "zh-cn" ? "设备名称" : "DeviceName" }}
              :</label>
            <div class="layui-input-inline">
              <input type="text" name="customName" id="customName" autocomplete="off" class="layui-input" />
            </div>
          </div>
          <div>
            <label class="layui-form-label">
              {{ i18n.language == "zh-cn" ? "设备组号" : "EquipmentGroupNumber" }}
              :</label>
            <div class="layui-input-inline">
              <input type="text" name="groupNum" id="groupNum" autocomplete="off" class="layui-input" />
            </div>
          </div>
        </div>
      </div>
    </form>
  </div>
  <div style="display: none; padding: 20px" id="groupNameDiv">
    <div class="layui-form-item">
      <div class="layui-form-item">
        <label class="layui-form-label">
          {{ i18n.language == "zh-cn" ? "组名" : "group" }}
          :</label>
        <div class="layui-input-block">
          <input type="text" name="groupName" id="groupName" lay-verify="required" autocomplete="off"
            class="layui-input" />
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
defineOptions({ name: "WiredDeviceList" });
import RightTableLayout from "@/views/workbench/components/RightTableLayout.vue";
import TreeTableLayout from "@/views/workbench/components/TreeTableLayout.vue";
import Tree from "@/components/tree.vue";
import { i18nStore } from "@/pinia/i18n";
const i18n = i18nStore();
const {
  appContext: {
    config: { globalProperties },
  },
} = getCurrentInstance();
let $httpUrl = globalProperties.$httpUrl;

let columns = reactive({ macaddress: { label: i18n.fy.MAC地址, queryValue: "" } });
let data = reactive({
  queryForm: {
    page: 1,
    limit: 100,
  },
  tableData: [],
  total: 0,
  dialog: false,
  form: {},
  rules: {
    name: [{ required: true, message: "请输入姓名", trigger: "change" }],
    role: [{ required: true, message: "请选择岗位", trigger: "change" }],
  },
});
const hex2int = (hex) => {
  if (hex == null || hex == "") {
    return;
  }

  var len = hex.length,
    a = new Array(len),
    code;
  for (var i = 0; i < len; i++) {
    code = hex.charCodeAt(i);
    if (48 <= code && code < 58) {
      code -= 48;
    } else {
      code = (code & 0xdf) - 65 + 10;
    }
    a[i] = code;
  }

  return a.reduce(function (acc, c) {
    acc = 16 * acc + c;
    return acc;
  }, 0);
};

const reQueryForm = () => {
  // 重置查询表单
  data.queryForm = {
    page: 1,
    limit: 100,
  };
};
const multipleTableRef = ref();
const multipleSelection = ref([]);
const toggleSelection = (rows) => {
  if (rows) {
    rows.forEach((row) => {
      // TODO: improvement typing when refactor table
      // eslint-disable-next-line @typescript-eslint/ban-ts-comment
      // @ts-expect-error
      multipleTableRef.value.toggleRowSelection(row, undefined);
    });
  } else {
    multipleTableRef.value.clearSelection();
  }
};
const handleSelectionChange = (val) => {
  multipleSelection.value = val;
};
let orderType = "";
let orderProp = "";
const sortChangeTable = (column, prop, order) => {
  orderType = column.order;
  orderProp = column.prop;
};
const loadTable = () => { };
const currentChange = (page) => {
  pageData.queryForm.page = page;
};

const sizeChange = (size) => {
  data.queryForm.page = size;
};

const add = () => {
  // 新增
};

const edit = (row) => {
  // 编辑
};
const onChanSize = (e) => {
  //修改分页数
  data.queryForm.page = 1;
  data.queryForm.limit = e;
  getList();
};
const onChanPage = (e) => {
  //修改分页
  data.queryForm.page = e;
  getList();
};

const del = (row) => {
  ElMessageBox.confirm("确认删除?", "提示").then(() => { });
};

let formRef = ref(null);

const submit = () => {
  // 提交新增/编辑表单
  formRef.value.validate((valid) => {
    if (valid) {
    }
  });
};
const getList = (params, num) => {
  // 获取表格数据
  data.loading = true;
  $axios
    .get("/operationDevice/queryOperationDeviceAllList", {
      ...data.queryForm,
      ...params,
      deviceFid: pid.value,
      limit: 10000,
      page: 1,
    })
    .then((res) => {
      if (res.data.data == null) {
        data.loading = false;
        return;
      }
      data.loading = false;
      data.tableData = res.data.data.records.slice((data.queryForm.page - 1) * data.queryForm.limit, data.queryForm.page * data.queryForm.limit);
      if (num == 1) {
        window.setTimeout(function () {
          data.tableData.forEach((row) => {
            multipleTableRef.value.toggleRowSelection(row);
          });
        }, 200);
      }

      data.total = res.data.data.total;
    });
};
let pid = ref("");
const doQuery = (params) => {
  if (params.deviceFid) {
    pid.value = params.deviceFid;
  }
  getDeviceAliasAllList();
  let num = 0;
  if (params.hasOwnProperty("macaddress")) {
    num = 1;
  } else {
    num = 0;
  }
  getList(params, 0);
  $.get($httpUrl + "/userLightNum/queryUserLightNum", { deviceFid: pid.value }, function (res) {
    if (res.data != null) {
      lightOnNum = res.data.lightOnNum;
      lightOffNum = res.data.lightOffNum;
    } else {
      lightOnNum = 40;
      lightOffNum = 0;
    }
  });
};
const showType = (type) => {
  if (type == -1) return "系统";
  if (type == 0) return "云平台";
  if (type == 1) return "云产品";
  if (type == 2) return "云设备";
};
//后台设定开灯值
var lightOnNum = 40;
//后台设定关灯值
var lightOffNum = 0;
//全局弹出
var mainIndex;
var $ = "";
var layer = "";
var form = "";
var table = "";
var dtree = "";
var slider = "";
var slider1 = "";
var slider2 = "";
var dropdown = "";
var maxNum = "";
var setTimeouts = "";
var tipsTime = "";
//渲染滑块
var lightNum = 0;
let total = 0;
let loading;
const getWidth = () => {
  return window.innerWidth - 398 + "px";
};
const getHeight = () => {
  return window.innerHeight - 240 + "px";
};
const allLightNum = () => {
  let lightNum1 = 0;
  let lightNum2 = 0;
  let ins1 = slider1.render({
    elem: "#slide1", //绑定元素
    input: true, //输入框
    min: 0,
    max: 100,
    value: lightOffNum,
    change: function (value) {
      lightNum1 = value;
    },
  });
  let ins2 = slider2.render({
    elem: "#slide2", //绑定元素
    input: true, //输入框
    min: 10,
    max: 100,
    value: lightOnNum,
    change: function (value) {
      lightNum2 = value;
    },
  });
  if (lightOnNum !== 0) {
    lightNum1 = lightOffNum;
    lightNum2 = lightOnNum;
  } else {
    lightNum1 = 0;
    lightNum2 = 20;
  }
  mainIndex = layer.open({
    type: 1,
    title: i18n.language === "zh-cn" ? "设置开关灯值" : "Set switch light value",
    content: $("#slideDiv2"),
    area: ["40%", "35%"],
    btnAlign: "c",
    btn: ['<div class="layui-icon layui-icon-release">确定</div>', '<div class="layui-icon layui-icon-close">取消</div>'],
    yes: function (index, layero) {
      $.post(
        $httpUrl + "/userLightNum/setUserLightNum",
        {
          deviceFid: pid.value,
          lightOnNum: lightNum2,
          lightOffNum: lightNum1,
        },
        function (res) {
          if (res.code === 200) {
            layer.msg("设置成功！");
            layer.close(mainIndex);
            lightOffNum = lightNum1;
            lightOnNum = lightNum2;
          } else {
            layer.msg("设置失败！");
          }
        }
      );
    },
  });
};
const allLightOn = () => {
  layer.confirm(i18n.language === "zh-cn" ? "确定设备全部开灯？" : "Are you sure all devices are on?", function (index) {
    loading = showLoad(i18n.language === "zh-cn" ? "全设备关灯请求中..." : "Request to turn off all devices...");
    $.post(
      $httpUrl + "/operation/multiOperation",
      {
        deviceId: pid.value,
        num: lightOnNum,
        operationalType: 0,
        macAddress: "FFFFFFFFFFFF",
      },
      function (res) {
        if (res.code == 3007) {
          layer.msg(res.msg);
          return false;
        }
        if (res.data != "fail") {
          layer.msg("全设备开灯请求成功!");
          let reqNum = 1;
        } else {
          layer.msg("全设备开灯失败!");
        }
      }
    );
  });
};
const allLightOff = () => {
  layer.confirm(i18n.language === "zh-cn" ? "确定设备全部关灯？" : "Are you sure all devices are turned off?", function (index) {
    loading = showLoad(i18n.language === "zh-cn" ? "全设备关灯请求中..." : "Request to turn off all devices...");
    $.post(
      $httpUrl + "/operation/multiOperation",
      {
        deviceId: pid.value,
        num: lightOffNum,
        operationalType: 2,
        //  gropuNum: $(".groupName").eq(0).html(),
        macAddress: "FFFFFFFFFFFF",
      },
      function (res) {
        if (res.code == 3007) {
          layer.msg(res.msg);
          return false;
        }
        if (res.data != "fail") {
          layer.msg("全设备关灯请求成功!");
          let reqNum = 1;
        } else {
          layer.msg("全设备关灯失败!");
        }
      }
    );
  });
};
const allLightAdjust = () => {
  mainIndex = layer.open({
    type: 1,
    title: i18n.language === "zh-cn" ? "调整全设备亮度:" : "Adjusting the brightness of the entire device",
    content: $("#slideDiv"),
    area: ["40%", "35%"],
    btnAlign: "c",
    btn: ['<div class="layui-icon layui-icon-release">确定</div>', '<div class="layui-icon layui-icon-close">取消</div>'],
    yes: function (index, layero) {
      layer.close(mainIndex);
      loading = showLoad(i18n.language === "zh-cn" ? "全设备调整亮度请求中..." : "Full device brightness adjustment request in progress...");
      $.post(
        $httpUrl + "/operation/multiOperation",
        {
          deviceId: pid.value,
          num: lightNum,
          operationalType: 1,
          macAddress: "FFFFFFFFFFFF",
        },
        function (res) {
          if (res.code == 3007) {
            layer.msg(res.msg);
            return false;
          }
          if (res.data != "fail") {
            layer.msg("全设备调整亮度请求成功！");
            let reqNum = 1;
          } else {
            layer.msg("全设备调整亮度失败!");
          }
        }
      );
    },
    success: function (index) { },
  });
};
const allAdjustColor = () => {
  mainIndex = layer.open({
    type: 1,
    title: i18n.language === "zh-cn" ? "调整设备色温:" : "Adjusting device color temperature",
    content: $("#slideDiv"),
    area: ["40%", "35%"],
    btnAlign: "c",
    btn: ['<div class="layui-icon layui-icon-release">确定</div>', '<div class="layui-icon layui-icon-close">取消</div>'],
    yes: function (index, layero) {
      layer.close(mainIndex);
      operationalType(5, lightNum, true);
    },
  });
};
const lightOn = () => {
  if (multipleSelection.value.length == 0) {
    layer.msg(i18n.language === "zh-cn" ? "还未选择设备！" : "No device has been selected yet!");
    return;
  }
  operationalType(0, lightOnNum);
};
const lightOff = () => {
  if (multipleSelection.value.length == 0) {
    layer.msg(i18n.language === "zh-cn" ? "还未选择设备！" : "No device has been selected yet!");
    return;
  }
  operationalType(2, lightOffNum);
};
const adjustLight = () => {
  if (multipleSelection.value.length == 0) {
    layer.msg(i18n.language === "zh-cn" ? "还未选择设备！" : "No device has been selected yet!");
    return;
  }
  let macs = multipleSelection.value
    .map((item) => {
      return item.macaddress;
    })
    .toString();
  mainIndex = layer.open({
    type: 1,
    title: "调整设备亮度:" + macs,
    content: $("#slideDiv"),
    area: ["40%", "35%"],
    btnAlign: "c",
    btn: ['<div class="layui-icon layui-icon-release">确定</div>', '<div class="layui-icon layui-icon-close">取消</div>'],
    yes: function (index, layero) {
      layer.close(mainIndex);
      loading = showLoad("设备调整亮度请求中...");
      $.post(
        $httpUrl + "/operation/adjustLight",
        {
          deviceId: pid.value,
          macAddress: macs,
          num: lightNum,
          operationalType: 1,
        },
        function (res) {
          if (res.code === 200) {
            layer.msg("设备调整亮度请求成功!");
          } else {
            layer.msg("设备调整亮度失败!");
          }
        }
      );
    },
    success: function (index) { },
  });
};
const adjustColor = () => {
  if (multipleSelection.value.length == 0) {
    layer.msg(i18n.language === "zh-cn" ? "还未选择设备！" : "No device has been selected yet!");
    return;
  }
  mainIndex = layer.open({
    type: 1,
    title: "调整设备色温",
    content: $("#slideDiv"),
    area: ["40%", "35%"],
    btnAlign: "c",
    btn: ['<div class="layui-icon layui-icon-release">确定</div>', '<div class="layui-icon layui-icon-close">取消</div>'],
    yes: function (index, layero) {
      layer.close(mainIndex);
      operationalType(5, lightNum);
    },
  });
};
//加载框
const showLoad = (msg, tipsTime = 0) => {
  return layer.msg(msg, {
    icon: 16,
    shade: [0.5, "#f5f5f5"],
    time: false,
    scrollbar: false,
    offset: "auto",
  });
};
const operationalType = (operationalType, num, allFlag) => {
  let macs = multipleSelection.value
    .map((item) => {
      return item.macaddress;
    })
    .toString();

  let typeList = ["开灯", "调灯", "关灯", "多灯测试开", "多灯测试关", "调整色温"];
  loading = showLoad(`${typeList[operationalType]}请求中...`);
  $.post(
    $httpUrl + "/operation/multiOperation",
    {
      deviceId: pid.value,
      macAddress: allFlag ? "FFFFFFFFFFFF" : macs,
      num: num === 0 || num ? num : 50, //50是测试的默认亮度
      operationalType: operationalType,
      gropuNum: "00",
    },
    function (res) {
      if (res.code == 3007) {
        layer.msg(res.msg);
        return false;
      }
      if (res.code === 200 && res.data === "success") {
        layer.msg(`${typeList[operationalType]}请求发送成功`);
      } else {
        layer.msg(`${typeList[operationalType]}请求发送失败`);
      }
    }
  );
};
let options = ref([]);
let customName = ref("全部");

const getDeviceAliasAllList = () => {
  if (!pid.value) {
    return false;
  }
  $.post(
    $httpUrl + "/operationDevice/deviceGroupAllList",
    {
      deviceFid: pid.value,
    },
    function (res) {
      options.value = res.data.filter((item) => {
        return item.group_name;
      });
      options.value.push({
        group_name: "全部",
        name: "全部",
      });
    }
  );
};
const setCustomName = () => {
  let params = {};
  if (customName.value == "全部") {
    params = { deviceFid: pid.value };
  } else {
    params = { groupName: customName.value, deviceFid: pid.value };
  }
  getList(params, 1);
};

onMounted(() => {
  total = 0;
  layui.extend({}).use(["jquery", "layer", "form", "table", "slider", "dropdown"], function () {
    $ = layui.jquery;
    layer = layui.layer;
    form = layui.form;
    table = layui.table;
    slider = layui.slider;
    slider1 = layui.slider;
    slider2 = layui.slider;
    dropdown = layui.dropdown;
    maxNum = 3;
    setTimeouts = 2000;
    tipsTime = 1000;
    //渲染滑块
    lightNum = 0;
    slider.render({
      elem: "#slideTest1", //绑定元素
      input: true, //输入框
      min: 0,
      change: function (value) {
        lightNum = value;
      },
    });
    getDeviceAliasAllList();
    getList({});
  });
});
</script>

<style lang="scss" scoped>
.available1 {
  color: orangered;
}

:deep(.selectName .el-input__wrapper) {
  background: none !important;
  box-shadow: none !important;
}

:deep(.selectName ::-webkit-input-placeholder) {
  color: #fff !important;
  text-align: right;
}

:deep(.selectName .el-select .el-input.is-focus .el-input__wrapper) {
  box-shadow: none !important;
}

:deep(.selectName input) {
  color: #fff !important;
}

:deep(.selectName select) {
  min-width: 80px;
  margin-left: 6px;
}

:deep(.selectName ::-webkit-input-placeholder) {
  color: #fff !important;
}

:deep(.btnbox .el-button + .el-button) {
  margin-left: 6px;
}
</style>
